﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace 用户管理系统
{
    public partial class DataSync : Form
    {
        public ConfigInfo configInfo = new ConfigInfo();
        private bool syncFlag = false;
        public DataSync()
        {
            InitializeComponent();
        }
        private void DataSync_Load(object sender, EventArgs e)
        {
            tssl_Status.Text = "状态：";
        }

        private async void btn_Sync_Click(object sender, EventArgs e)
        {
            switch (btn_Sync.Text)
            {
                case "开始同步":
                    btn_Sync.Text = "停止同步";
                    syncFlag = true;
                    await Task.Run(() => { Sync(); });
                    btn_Sync.Text = "开始同步";
                    break;
                default:
                    btn_Sync.Text = "开始同步";
                    syncFlag = false;
                    break;
            }


        }

        private void Sync()
        {
            MyServer myServer = new MyServer();
            MyJson myJson = new MyJson();
            string urlFlag = "data_sync";
            PostData postData = new PostData()
            {
                action = "S",
                limit = 50
            };
            while (syncFlag)
            {
                MyData myData = new MyData(myServer);
                ResData resData = myData.DataSync(urlFlag, postData);
                if (resData.code == 0)
                {
                    resData.datas.ForEach(item =>
                    {
                        UpdateText(item);
                    });
                    UpdateStatus($"状态：总记录{resData.count}");
                } else if (resData.code == 99)
                {
                    syncFlag = false;
                    UpdateStatus($"状态：同步完成");
                }
                Thread.Sleep(200);
            }
        }

        private void UpdateText(string text)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(()=>UpdateText(text)));
            }
            else
            {
                txt_Log.AppendText(text+"\r\n");
            }
        }

        private void UpdateStatus(string text)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(text)));
            }
            else
            {
                tssl_Status.Text = text;
            }
        }
    }
}
